document.querySelector("html").style.fontSize = (window.innerWidth / 16) + "px";
window.onorientationchange = () => {
  window.location.reload();
};

const api = "https://jdb-demo.4ukids.cn/api/";
const evaluatingUrl = "https://test.qhrunjin.com/api/";
const evaluatingTokenId = "1459219202000001";
const over = document.getElementById("over");
const wxAudio = {
  audioType: "amr",
  sampleRate: 8000,
  channel: 1,
  sampleBytes: 2
};

var gd = [];
var ah = 0;
var model = 0;

aid = "";
sid = "";

var rec = Recorder({
  type: "mp3",
  sampleRate: 44100,
  bitRate: 320,
  // type: "wav",
  // sampleRate: 41001,
  // bitRate: 1411, //mp3格式，指定采样率hz、比特率kbps，其他参数使用默认配置；注意：是数字的参数必须提供数字，不要用字符串；需要使用的type类型，需提前把格式支持文件加载进来，比如使用wav格式需要提前加载wav.js编码引擎
  onProcess: function (buffers, powerLevel, bufferDuration, bufferSampleRate, newBufferIdx, asyncEnd) { }
});
// setModel();



const gParams = getParams();
function getParams() {
  return JSON.parse(decodeURIComponent(window.location.href.split("?data=")[1]));
}
// console.log(gParams);
window.onload = () => {
  setModel();
  send({
    url: api + "video/dubbing",
    headers: { "ACCESS-TOKEN": "0F242BEB-33A4-7CFB-BA85-950EC16F8485" },
    data: { video_id: gParams.value },
    success(res) {
      if (res.errorcode == 0) {
        gd = res.data;
        $(".container").append(createDom(gd));
        let t = $(`<div class="result">查看结果</div>`);
        t.unbind("click").click(e => {
          if (gParams.mix_video_url) {
            window.location.href = "./player.html?data=" + encodeURIComponent(JSON.stringify({
              video: {
                url: gParams.mix_video_url,
                pic: gParams.pic
              }
            }));
          }
        });
        $(".container").append(t);

        $(".fill").unbind("click");
        $(".dubbtn").unbind("click").click(e => {
          let p = $(e.currentTarget).parents("div .dubcard");
          let b = p.find("div .probar");
          let i = Number(p.attr("id"));
          playAudio({
            audios: p.find("audio"), success: r => {
              startRec({
                duration: gd[i].section_duration, probar: b, params: { index: i },
                success: res => {

                  if (!model) gd[res.index].audio = $(`<audio src=${(window.URL || webkitURL).createObjectURL(res.source)} />`);
                  p.find(".dubwarn").text("配音完毕!点击播放按钮播放.");
                  gd[res.index].source = res.source;
                  if (res.source) evaluating({
                    index: res.index,
                    param: {
                      request: {
                        refText: gd[res.index].section_text_en,
                        precision: 1,
                        rank: 5,
                        tokenId: evaluatingTokenId
                      },
                      audio: model === 0 ? {
                        audioType: "mp3",
                        sampleRate: 44100,
                        channel: 1,
                        sampleBytes: 2
                      } : wxAudio
                    },
                    success(res) {
                      console.log(res);
                      over.play();
                    }
                  });
                  // console.log(gd[res.index], gParams);
                  const d = new FormData();
                  d.append("video_id", gParams.value);
                  d.append("file", gd[res.index].source);
                  d.append("section_no", gd[res.index].section_no);
                  if (res.source) send({
                    // url: api + "mixVideoByH5",
                    url: api + "uploadFileByH5",
                    headers: { "ACCESS-TOKEN": "0F242BEB-33A4-7CFB-BA85-950EC16F8485" },
                    data: d,
                    success(res) {
                      for (let i = 0; i < gd.length; i++) {
                        if (!gd[i].source) return;
                      }
                      console.log(1, res);
                      send({
                        url: api + "mixVideoByH5",
                        headers: { "ACCESS-TOKEN": "0F242BEB-33A4-7CFB-BA85-950EC16F8485" },
                        data: { video_id: gParams.value },
                        success(res2) {
                          console.log(2, res2);
                          if (res2.data && res2.data.mix_video_url) {
                            gParams.mix_video_url = res2.data.mix_video_url;
                          }
                        }
                      });
                    }
                  });
                }
              });
            }
          }, () => { b.width(0); });
          return false;
        });
        $(".replaybtn").unbind("click").click(e => {
          let i = Number($(e.currentTarget).parents("div .dubcard").attr("id"));
          // alert(gd[i].audio[0].src);
          switch (model) {
            case 0:
              if (gd[i].audio) gd[i].audio[0].play();
              break;
            case 1:
              console.log("启用微信播放", gd[i]);
              if (gd[i].wxAudio) wx.playVoice({ localId: gd[i].wxAudio });
              break;
            case 2:
              console.log("使用u3d播放", gd[i]);
              window.location.href = "uniwebview://U3D_PlayRecordFile?request_id=" + gd[i].u3dAudio;
              break;

            default:
              break;
          }
          console.log(gd[i].section_duration);
          return false;
        });
      }
    }
  });
};
function playAudio(params, before) {
  if (typeof before == "function") before();
  if (typeof params != "object" || typeof params.audios != "object" || params.audios.length < 0) return;
  if (!(params.i > 0)) {
    try {
      over.currentTime = 0;
      over.addEventListener("play", overPause);
      over.play();
      over.pause();
    } catch (error) {

    }
    params.i = 0;
    for (let i = 0; i < params.audios.length; i++) {
      params.audios[i].play();
      params.audios[i].pause();
    }
  }
  if (params.audios.length > params.i) {
    params.audios.eq(params.i).unbind("ended").bind("ended", () => {
      params.i++;
      playAudio(params);
    });
    // params.audios[params.i].load();
    params.audios[params.i].play();
    // params.audios[0].play();
  } else {
    if (typeof params.success == "function") params.success();
  }
}
function send(params) {
  if (typeof params == "object") {
    let data = params.data;
    if (!(params.data instanceof FormData) && typeof params.data == "object") {
      data = JSON.stringify(params.data);
    }
    if (typeof params.contentType == "undefined") {
      params.contentType = typeof data == "object" ? false : "application/json";
    }
    const ap = {
      url: params.url,
      type: params.type == "get" ? "get" : "post",
      data: data,
      cache: false,
      processData: false,
      contentType: params.contentType,
      dateType: "JSON",
      success(res) {
        let t = false;
        try {
          t = JSON.parse(res);
        } catch (error) {
          console.log(res);
          console.log(error);
          console.log(ap);
        }
        if (t) {
          params.success(t);
        }
      },
      error: params.error
    };

    if (params.headers) ap.headers = params.headers;
    $.ajax(ap);
  } else {
    console.error("参数类型错误.参数类型必须为object");
  }
}
function getStar(params, n) {
  let r = "";
  if (!(n && n > 0)) n = 0;
  for (let i = 0; i < params; i++) {
    r += `<img class='rate' src='img/star_${i < n ? 'fill' : 'empty'}.png' />`;
  }
  return r;
}
function createDom(params) {
  let l = params.length;
  let r = `
<div class="videotop">
  <div class="videotitle">${gParams.title}</div>
  <div class="videorate"><div class="nbx">级别</div><div class="rateimg">${getStar(5, gParams.rank)}</div></div>
</div>
<div class="mainarea">`;
  for (let i = 0; i < l; i++) {
    r += `
<div class="dubcard" id=${i} value=${params[i].section_duration}>
  <div class="dubtop"><div class="nbx">${params[i].section_no}/${l}</div><div class="cardrate">${getStar(5)}</div></div>
  <div class="dubword">${params[i].section_text_en}</div>
  <div class="dubwarn">还未配音,请点击麦克风配音!</div>
  <div class="cutline"></div>
  <div class="dubbot">
    <div class="dubline">
      <div class="probar"></div>
    </div><div class="nbx">${params[i].section_duration}s</div><audio preload class="dubaudio" src="${params[i].section_orign_sound}"></audio>
      <audio preload class="readagain" src="./audio/readAgain.mp3"></audio>
      <div class="dubbtn"><img class="fill" src="./img/dubstart.png" /></div>
      <div class="replaybtn"><img class="fill" src="./img/dubplay.png" /></div>
  </div>
</div>`;
  }
  return r + "</div>";
}
function startRec(params) {
  // console.log(params,gd);
  // rec.start();
  if (ah) {
    clearInterval(ah);
    stopRec();
  }
  if (params.duration > 0) {
    params.duration++;
  } else {
    params.duration = 10;
  }
  let t = 0;

  switch (model) {
    case 0:
      rec.start();
      break;
    case 1:
      wx.ready(function () {
        wx.startRecord({
          success: function () {
            console.log("开始wx录音");
          },
          fail: function (res) {
            console.log('微信开启录音失败', res);
          },
          cancel: function () {
            console.log('微信拒绝授权');
          }
        });
      });
      break;
    case 2:
      window.location.href = "uniwebview://U3D_StartRecord?type=" + gd[params.params.index].section_type + "&content=" + gd[params.params.index].section_text_en;
      break;
    default:
      break;
  }

  ah = setInterval(() => {
    if (t < 100) {
      t++;
      if (params.probar) params.probar.width(t + "%");
    } else {
      clearInterval(ah);
      ah = 0;
      if (typeof params.params != "object") params.params = {};
      stopRec(params);
    }
  }, params.duration * 10);

}
function stopRec(params) {
  console.log(params);
  switch (model) {
    case 0:
      rec.stop(blob => {
        if (params && params.params) {
          params.params.source = blob;
          if (typeof params.success == "function") params.success(params.params);
        }
      });
      break;
    case 1:
      wx.stopRecord({
        fail: function (res) {
          console.log('微信 停止录音失败', res);
        },
        success: function (resStop) {
          console.log('微信 停止录音成功', resStop.localId == aid);
          if (params && params.params) {
            aid = resStop.localId;
            gd[params.params.index].wxAudio = aid;
            wx.uploadVoice({
              localId: aid,
              isShowProgressTips: 0,
              success: function (res) {
                // res.serverId = "9mTgoRhZMh1Gn1qDruA_ULk5HCwBmih4nBQSk9KBybbwUw8JEDdd5kKSpJMKSGpW";
                const url = 'https://file.api.weixin.qq.com/cgi-bin/media/get?access_token=' + wxToken + '&media_id=' + res.serverId;
                aurl = url;
                send({
                  contentType: false,
                  url: evaluatingUrl,
                  // url:"https://test.nanme.top/api",
                  data: { getFile: url },
                  success(r) {
                    gb = new Blob([base64ToUint8Array(r.file)], { type: "audio/" + wxAudio.audioType });
                    params.params.source = gb;
                    if (typeof params.success == "function") params.success(params.params);
                  }
                });
              },
              fail: function (res) {
                console.log('微信 上传 失败', res, resStop, localId);
              }
            });
          }
        }
      });
      break;
    case 2:
      if (params) {
        u3dParams = params;
      } else {
        u3dParams = null;
      }
      window.location.href = "uniwebview://U3D_StopRecord";
      break;
    default:
      break;
  }
}
function JS_ResponseEvaluateResult_U3D(errorCode, overallScore, id, source, msg) {
  console.log("u3d返回", errorCode, msg, overallScore, parseInt(overallScore / 20));
  console.log(source);
  console.log(base64ToUint8Array(source));
  console.log("u3dParams", u3dParams);
  if (u3dParams) {
    gd[u3dParams.params.index].pron = parseInt(overallScore / 20);
    if (parseInt(errorCode)) {
      u3dParams.probar.width(0);
    } else {
      u3dParams.params.source = new Blob([base64ToUint8Array(source)], { type: "audio/" + wxAudio.audioType });
    }
    gd[u3dParams.params.index].u3dAudio = id;
    if (typeof u3dParams.success == "function") u3dParams.success(u3dParams.params);
  }
}

function evaluating(params) {
  const f = new FormData();
  if (model == 1) {
    params.param.audio = wxAudio;
  }
  f.append("h5", JSON.stringify({ param: params.param }));
  f.append("audio", gd[params.index].source);

  if (model < 2) {
    send({
      url: params.url ? params.url : evaluatingUrl,
      data: f,
      success: r => {
        $("#" + params.index).find("div .cardrate img").slice(0, r.pron).attr("src", "img/star_fill.png");
        if (typeof params.success == "function") params.success(r);
      },
      error: params.error
    });
  } else {
    $("#" + params.index).find("div .cardrate img").slice(0, gd[params.index].pron).attr("src", "img/star_fill.png");
    if (typeof params.success == "function") params.success(gd[params.index]);
  }
}
function rw() {
  const config = {
    debug: false,
    url: location.href,
    // url: window.location.href.split("?data=")[0],
    // url: "https://test.qhrunjin.com/dubbing/videoplay.html?data={%22value%22:1,%22img%22:%22http://jdb-demo.oss-cn-zhangjiakou.aliyuncs.com/video/1/cover_small.jpg%22}",
  }
  send({
    contentType: false,
    url: evaluatingUrl,
    // url:"https://test.nanme.top/api",
    data: config,
    success(r) {
      if (typeof r.debug == 'undefined') r.debug = WXconfig.debug;
      if (typeof r.token == 'undefined') r.token = r.accessToken;
      // console.log(r);
      wxToken = r.token
      wxCon = {
        debug: r.debug,
        appId: r.appId,
        timestamp: r.timestamp,
        nonceStr: r.nonceStr,
        signature: r.signature,
        jsApiList: [
          'startRecord',
          'stopRecord',
          'playVoice',
          'pauseVoice',
          'stopVoice',
          'onVoicePlayEnd',
          'uploadVoice',
          "downloadVoice",
          'checkJsApi',
          'getLocalImgData',
        ]
      };
      wx.ready(function () {
        console.clear();
      });
      wx.error(function (res) {
        console.log('微信jssdk失败', res, wxCon, r);
      });
      wx.config(wxCon);

    }
  });
}
function setModel() {
  const ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i)) {
    model = 1;
    rw();
  } else if (ua.match(/Native_Unity3D/i)) {
    model = 2;
  } else {
    rec.open(function () { //打开麦克风授权获得相关资源
      // console.log("已打开录音，可以点击录制开始录音了");
    }, function (msg, isUserNotAllow) { //用户拒绝未授权或不支持
      alert("您的设备不支持录音或没有相关权限!");
      console.log((isUserNotAllow ? "UserNotAllow，" : "") + "打开录音失败：" + msg, 1);
    });
  }
}
function upa(params) {
  send({
    contentType: false,
    url: evaluatingUrl,
    // url:"https://test.nanme.top/api",
    data: { getFile: aurl },
    success(r) {
      console.log(r);
    }
  });

  return;
  evaluating({
    index: 1,
    param: {
      request: {
        refText: gd[1].section_text_en,
        precision: 1,
        rank: 5,
        tokenId: evaluatingTokenId
      },
      audio: {
        audioType: "mp3",
        sampleRate: 44100,
        channel: 1,
        sampleBytes: 2
      }
    },
    success(res) {
      console.log(res);
    }
  });
}
function base64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g, '+')
    .replace(/_/g, '/');

  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}
function overPause() {
  over.removeEventListener("play", overPause);
  console.log("暂停了");
  over.pause();
}
// console.log(123, window.location.href.split("?data=")[0]);